<template>
  <div class="monitor-analysis">
    <!-- 时间范围选择 -->
    <div class="analysis-header">
      <el-form :inline="true" :model="queryParams" class="query-form">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="timeShortcuts"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleTimeRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleExport">导出分析报告</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>系统健康度</span>
              <el-tag :type="getHealthStatusType(healthData.score)">{{ healthData.score }}%</el-tag>
            </div>
          </template>
          <div class="card-content">
            <el-progress
              :percentage="healthData.score"
              :status="getHealthStatusType(healthData.score)"
              :stroke-width="15"
            />
            <div class="data-detail">
              <p>CPU使用率: {{ healthData.cpuUsage }}%</p>
              <p>内存使用率: {{ healthData.memoryUsage }}%</p>
              <p>磁盘使用率: {{ healthData.diskUsage }}%</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>性能指标</span>
              <el-tag type="success">良好</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="metric-item">
              <span class="label">平均响应时间</span>
              <span class="value">{{ performanceData.avgResponseTime }}ms</span>
            </div>
            <div class="metric-item">
              <span class="label">QPS</span>
              <span class="value">{{ performanceData.qps }}</span>
            </div>
            <div class="metric-item">
              <span class="label">错误率</span>
              <span class="value">{{ performanceData.errorRate }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>告警统计</span>
              <el-tag :type="getAlertStatusType(alertData.total)">{{ alertData.total }}个</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="metric-item">
              <span class="label">严重告警</span>
              <span class="value danger">{{ alertData.critical }}</span>
            </div>
            <div class="metric-item">
              <span class="label">警告</span>
              <span class="value warning">{{ alertData.warning }}</span>
            </div>
            <div class="metric-item">
              <span class="label">已处理</span>
              <span class="value success">{{ alertData.resolved }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>资源使用</span>
              <el-tag type="info">实时</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="metric-item">
              <span class="label">CPU使用率</span>
              <el-progress :percentage="resourceData.cpu" :status="getResourceStatusType(resourceData.cpu)" />
            </div>
            <div class="metric-item">
              <span class="label">内存使用率</span>
              <el-progress :percentage="resourceData.memory" :status="getResourceStatusType(resourceData.memory)" />
            </div>
            <div class="metric-item">
              <span class="label">磁盘使用率</span>
              <el-progress :percentage="resourceData.disk" :status="getResourceStatusType(resourceData.disk)" />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 趋势图表 -->
    <el-row :gutter="20" class="trend-charts">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>性能趋势</span>
              <el-radio-group v-model="performanceChartType" size="small">
                <el-radio-button label="response">响应时间</el-radio-button>
                <el-radio-button label="qps">QPS</el-radio-button>
                <el-radio-button label="error">错误率</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="performanceChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>资源使用趋势</span>
              <el-radio-group v-model="resourceChartType" size="small">
                <el-radio-button label="cpu">CPU</el-radio-button>
                <el-radio-button label="memory">内存</el-radio-button>
                <el-radio-button label="disk">磁盘</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="resourceChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="trend-charts">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>告警趋势</span>
              <el-select v-model="alertChartType" size="small">
                <el-option label="告警数量" value="count" />
                <el-option label="告警类型分布" value="type" />
                <el-option label="告警级别分布" value="level" />
              </el-select>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="alertChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>API调用分布</span>
              <el-select v-model="apiChartType" size="small">
                <el-option label="调用次数" value="count" />
                <el-option label="响应时间" value="time" />
                <el-option label="错误率" value="error" />
              </el-select>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="apiChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分析报告 -->
    <el-card shadow="hover" class="analysis-report">
      <template #header>
        <div class="card-header">
          <span>系统分析报告</span>
          <el-button type="primary" link @click="handleGenerateReport">生成报告</el-button>
        </div>
      </template>
      <div class="report-content">
        <el-collapse v-model="activeReportItems">
          <el-collapse-item title="系统健康分析" name="health">
            <div class="report-section">
              <h4>系统整体状况</h4>
              <p>{{ reportData.health.overview }}</p>
              <h4>主要问题</h4>
              <ul>
                <li v-for="(issue, index) in reportData.health.issues" :key="index">
                  {{ issue }}
                </li>
              </ul>
              <h4>优化建议</h4>
              <ul>
                <li v-for="(suggestion, index) in reportData.health.suggestions" :key="index">
                  {{ suggestion }}
                </li>
              </ul>
            </div>
          </el-collapse-item>
          <el-collapse-item title="性能分析" name="performance">
            <div class="report-section">
              <h4>性能概况</h4>
              <p>{{ reportData.performance.overview }}</p>
              <h4>性能瓶颈</h4>
              <ul>
                <li v-for="(bottleneck, index) in reportData.performance.bottlenecks" :key="index">
                  {{ bottleneck }}
                </li>
              </ul>
              <h4>优化方案</h4>
              <ul>
                <li v-for="(solution, index) in reportData.performance.solutions" :key="index">
                  {{ solution }}
                </li>
              </ul>
            </div>
          </el-collapse-item>
          <el-collapse-item title="资源分析" name="resource">
            <div class="report-section">
              <h4>资源使用概况</h4>
              <p>{{ reportData.resource.overview }}</p>
              <h4>资源预警</h4>
              <ul>
                <li v-for="(warning, index) in reportData.resource.warnings" :key="index">
                  {{ warning }}
                </li>
              </ul>
              <h4>资源优化建议</h4>
              <ul>
                <li v-for="(suggestion, index) in reportData.resource.suggestions" :key="index">
                  {{ suggestion }}
                </li>
              </ul>
            </div>
          </el-collapse-item>
          <el-collapse-item title="告警分析" name="alert">
            <div class="report-section">
              <h4>告警概况</h4>
              <p>{{ reportData.alert.overview }}</p>
              <h4>高频告警</h4>
              <ul>
                <li v-for="(alert, index) in reportData.alert.frequentAlerts" :key="index">
                  {{ alert }}
                </li>
              </ul>
              <h4>告警处理建议</h4>
              <ul>
                <li v-for="(suggestion, index) in reportData.alert.suggestions" :key="index">
                  {{ suggestion }}
                </li>
              </ul>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { ElMessage } from 'element-plus'
import {
  getSystemHealthData,
  getSystemPerformanceData,
  getSystemResources,
  getPerformanceTrend,
  getResourceTrend,
  getAlertTrend,
  getApiDistribution,
  getLogStatistics,
  exportAnalysisReport,
  generateAnalysisReport
} from '@/api/message'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

// 查询参数
const queryParams = reactive({
  timeRange: []
})

// 时间快捷选项
const timeShortcuts = [
  {
    text: '最近一天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24)
      return [start, end]
    }
  },
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  }
]

// 图表类型
const performanceChartType = ref('response')
const resourceChartType = ref('cpu')
const alertChartType = ref('count')
const apiChartType = ref('count')

// 数据概览
const healthData = reactive({
  score: 0,
  cpuUsage: 0,
  memoryUsage: 0,
  diskUsage: 0
})

const performanceData = reactive({
  avgResponseTime: 0,
  qps: 0,
  errorRate: 0
})

const alertData = reactive({
  total: 0,
  critical: 0,
  warning: 0,
  resolved: 0
})

const resourceData = reactive({
  cpu: 0,
  memory: 0,
  disk: 0
})

// 报告数据
const reportData = reactive({
  health: {
    overview: '',
    issues: [],
    suggestions: []
  },
  performance: {
    overview: '',
    bottlenecks: [],
    solutions: []
  },
  resource: {
    overview: '',
    warnings: [],
    suggestions: []
  },
  alert: {
    overview: '',
    frequentAlerts: [],
    suggestions: []
  }
})

// 报告折叠面板
const activeReportItems = ref(['health'])

// 图表配置
const performanceChartOption = computed(() => ({
  title: {
    text: '性能趋势分析'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: performanceChartType.value === 'response' ? '响应时间' : 
            performanceChartType.value === 'qps' ? 'QPS' : '错误率',
      type: 'line',
      data: [],
      smooth: true
    }
  ]
}))

const resourceChartOption = computed(() => ({
  title: {
    text: '资源使用趋势'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: '{value}%'
    }
  },
  series: [
    {
      name: resourceChartType.value === 'cpu' ? 'CPU使用率' :
            resourceChartType.value === 'memory' ? '内存使用率' : '磁盘使用率',
      type: 'line',
      data: [],
      smooth: true,
      areaStyle: {}
    }
  ]
}))

const alertChartOption = computed(() => ({
  title: {
    text: '告警趋势分析'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '告警数量',
      type: 'bar',
      data: []
    }
  ]
}))

const apiChartOption = computed(() => ({
  title: {
    text: 'API调用分析'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: apiChartType.value === 'count' ? '调用次数' :
            apiChartType.value === 'time' ? '响应时间' : '错误率',
      type: 'bar',
      data: []
    }
  ]
}))

// 初始化
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  try {
    // 加载健康数据
    const healthRes = await getSystemHealthData()
    Object.assign(healthData, healthRes.data)

    // 加载性能数据
    const performanceRes = await getSystemPerformanceData()
    Object.assign(performanceData, performanceRes.data)

    // 加载资源数据
    const resourceRes = await getSystemResources()
    Object.assign(resourceData, resourceRes.data)

    // 加载告警数据
    const alertRes = await getLogStatistics()
    Object.assign(alertData, alertRes.data)

    // 加载趋势数据
    await loadTrendData()

    // 生成分析报告
    await generateReport()
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

// 加载趋势数据
const loadTrendData = async () => {
  try {
    const params = {
      startTime: queryParams.timeRange[0],
      endTime: queryParams.timeRange[1]
    }

    // 加载性能趋势
    const performanceTrendRes = await getPerformanceTrend(params)
    updatePerformanceChart(performanceTrendRes.data)

    // 加载资源趋势
    const resourceTrendRes = await getResourceTrend(params)
    updateResourceChart(resourceTrendRes.data)

    // 加载告警趋势
    const alertTrendRes = await getAlertTrend(params)
    updateAlertChart(alertTrendRes.data)

    // 加载API分布
    const apiDistributionRes = await getApiDistribution(params)
    updateApiChart(apiDistributionRes.data)
  } catch (error) {
    console.error('加载趋势数据失败:', error)
    ElMessage.error('加载趋势数据失败')
  }
}

// 更新图表数据
const updatePerformanceChart = (data) => {
  // 更新性能趋势图表数据
}

const updateResourceChart = (data) => {
  // 更新资源趋势图表数据
}

const updateAlertChart = (data) => {
  // 更新告警趋势图表数据
}

const updateApiChart = (data) => {
  // 更新API分布图表数据
}

// 生成分析报告
const generateReport = async () => {
  try {
    const res = await generateAnalysisReport({
      startTime: queryParams.timeRange[0],
      endTime: queryParams.timeRange[1]
    })
    Object.assign(reportData, res.data)
  } catch (error) {
    console.error('生成分析报告失败:', error)
    ElMessage.error('生成分析报告失败')
  }
}

// 事件处理
const handleTimeRangeChange = () => {
  loadTrendData()
}

const handleQuery = () => {
  loadData()
}

const handleReset = () => {
  queryParams.timeRange = []
  loadData()
}

const handleExport = async () => {
  try {
    await exportAnalysisReport({
      startTime: queryParams.timeRange[0],
      endTime: queryParams.timeRange[1]
    })
    ElMessage.success('导出分析报告成功')
  } catch (error) {
    console.error('导出分析报告失败:', error)
    ElMessage.error('导出分析报告失败')
  }
}

const handleGenerateReport = () => {
  generateReport()
}

// 工具方法
const getHealthStatusType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 70) return 'warning'
  return 'danger'
}

const getAlertStatusType = (count) => {
  if (count === 0) return 'success'
  if (count <= 5) return 'warning'
  return 'danger'
}

const getResourceStatusType = (usage) => {
  if (usage >= 90) return 'exception'
  if (usage >= 70) return 'warning'
  return 'success'
}
</script>

<style lang="scss" scoped>
.monitor-analysis {
  padding: 20px;

  .analysis-header {
    margin-bottom: 20px;

    .query-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }

  .data-overview {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-content {
      .data-detail {
        margin-top: 10px;
        p {
          margin: 5px 0;
          color: #666;
        }
      }

      .metric-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 10px 0;

        .label {
          color: #666;
        }

        .value {
          font-weight: bold;

          &.danger {
            color: #f56c6c;
          }

          &.warning {
            color: #e6a23c;
          }

          &.success {
            color: #67c23a;
          }
        }
      }
    }
  }

  .trend-charts {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chart-container {
      height: 300px;
    }
  }

  .analysis-report {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .report-section {
      h4 {
        margin: 15px 0 10px;
        color: #303133;
      }

      p {
        color: #606266;
        line-height: 1.6;
      }

      ul {
        padding-left: 20px;
        color: #606266;
        line-height: 1.8;

        li {
          margin: 5px 0;
        }
      }
    }
  }
}
</style> 